package com.duowei.diandan.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.duowei.diandan.R;
import com.duowei.diandan.app.InitManager;
import com.duowei.diandan.app.OrderList;
import com.duowei.diandan.constant.Settings;
import com.duowei.diandan.db.entry.Auth;
import com.duowei.diandan.db.entry.Jgsz;
import com.duowei.diandan.fragment.dialog.AuthDialogFragment;
import com.duowei.diandan.fragment.dialog.InputDialogFragment;
import com.duowei.diandan.util.FileUtils;
import com.duowei.diandan.util.NetUtils;
import com.duowei.diandan.util.ToastUtils;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.loader.ImageLoader;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * 开始屏
 */
@RuntimePermissions
public class WelcomeActivity extends BaseActivity {
    private static final String TAG = "WelcomeActivity";

    private ImageView mDefaultView;
    private Banner mBanner;

    private View.OnClickListener mOnClickListener = v ->
            startActivity(new Intent(WelcomeActivity.this, ContainerActivity.class));

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: ");
        setContentView(R.layout.activity_welcome);
        initView();
        InitManager.getInstance().setCanDownTime(false);
        OrderList.getInstance().resetCurrentMemberGrade();

        getAuthData();
    }

    private void getAuthData() {
        new Thread(() -> {
            String authUrl="http://androidwww.wxdw.top:2233/androidauth/ServerSvlt?";
            String packageName = getPackageName();
            String androidID = android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
            String serialNumber=android.os.Build.SERIAL;
            String id = "unknown".equals(serialNumber)?androidID:serialNumber;
            String authSql="call prc_androidauth_forever('"+id+"','"+packageName+"')|";
            List<Auth> authList = null;
            try {
                authList = NetUtils.post6(authUrl, authSql, Auth.class);
                Auth auth = authList.get(0);
                if(!"1".equals(auth.getIsforver())){
                    AuthDialogFragment fragment = AuthDialogFragment.newInstance(auth);
                    fragment.show(getSupportFragmentManager(),null);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mBanner.startAutoPlay();

        getDb().dcczDao().deleteAll();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mBanner.stopAutoPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }

    private void initView() {
        mDefaultView = findViewById(R.id.defaultImage);
        mBanner = findViewById(R.id.banner);

        mDefaultView.setOnClickListener(mOnClickListener);
        mBanner.setOnBannerListener(position -> mOnClickListener.onClick(null));
        findViewById(R.id.tv_click).setOnClickListener(mOnClickListener);


        int imagePlayTime = Settings.IMAGE_PLAY_TIME;
        WelcomeActivityPermissionsDispatcher.setPlayImageWithPermissionCheck(this, imagePlayTime);

        // 设置
        ViewGroup settingLayout = findViewById(R.id.settingLayout);
        Button settingButton = findViewById(R.id.settingButton);
        if (Settings.HIDE_SETTING_BUTTON) {
            settingButton.setVisibility(View.INVISIBLE);
            settingLayout.setOnClickListener(view -> {
                showUserAuthDialogFragment();
            });
        } else {
            settingButton.setVisibility(View.VISIBLE);
            settingButton.setOnClickListener(view -> {
                showUserAuthDialogFragment();
            });
        }
    }

    private void showUserAuthDialogFragment() {
        InputDialogFragment fragment = InputDialogFragment.newInstanceInputPassword();
        fragment.setOkBtnClickListener(text -> {
            if (getString(R.string.password).equals(text)) {
                SettingsActivity.openSettingsActivity(this);
            } else {
                Toast.makeText(this, "密码错误", Toast.LENGTH_SHORT).show();
            }
        });
        fragment.show(getSupportFragmentManager(), null);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        WelcomeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void setPlayImage(int time) {
        FileUtils.initWelcomeFolder();

        File file = new File(Environment.getExternalStorageDirectory(), "/Dw/welcome_images");
        File[] imageArray = file.listFiles((dir, name) -> !name.equals(".nomedia"));
        if (imageArray == null) {
            // 未发现图片
            mDefaultView.setVisibility(View.VISIBLE);
            mBanner.setVisibility(View.GONE);
        } else {
            List<File> imageList = Arrays.asList(imageArray);
            if (imageList.size() == 0) {
                // 未发现图片
                mDefaultView.setVisibility(View.VISIBLE);
                mBanner.setVisibility(View.GONE);

            } else {
                mDefaultView.setVisibility(View.GONE);
                mBanner.setVisibility(View.VISIBLE);

                mBanner.setImages(imageList);
                mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
                // mBanner.setIndicatorGravity(BannerConfig.RIGHT);
                mBanner.setImageLoader(new WelcomeImageLoader());
                mBanner.isAutoPlay(true);
                mBanner.setDelayTime(time * 1000);
                mBanner.start();
            }
        }
    }

    private class WelcomeImageLoader extends ImageLoader {

        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Picasso.with(context).load((File) path).fit().centerCrop().into(imageView);
        }
    }
}
